package com.zzyl.intercept;

import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @param
 * @return
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");
        //判断token是否为空
        if (token == null || token == "") {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        try {
            //解析token
            Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
            if (claims == null || claims.isEmpty()) {
                //有token解析token时claims集合为空 也抛一个异常
                throw new BaseException(BasicEnum.LOGIN_FAIL);
            }
            //解析成功
            Integer id = (Integer) claims.get("id");
            int intId = id;
            UserThreadLocal.set(Long.valueOf(intId));
        } catch (Exception e) {
            //解析不成功
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //满足上述要求放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应结束，需清理ThreadLocal中的数据，防止内存泄漏
        UserThreadLocal.remove();
    }
}
